﻿using System;
using NAudio.Wave;
using NAudio.Utils;

namespace PT.NoteDetection.Wave {

    /// <summary>
    /// Special purpouse class for buffering captured data
    /// Essentially allows reads and writes, by writing to a bigger buffer
    /// </summary>
    public class CaptureStream : WaveStream {

        static readonly WaveFormat Format;

        const int SampleRate = 44100;
        const int Channels = 1;

        readonly CircularBuffer buf;
        long totalBytes;

        static CaptureStream() {
            Format = WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, Channels);
        }

        public CaptureStream(int bufferLengthMilliseconds) {

            var bufferLength = 
                bufferLengthMilliseconds * Format.SampleRate * Format.BitsPerSample / 8 
                / 1000;
            
            buf = new CircularBuffer(bufferLength);
        }

        public override bool CanRead { get { return true; } }

        public override bool CanWrite { get { return true; } }

        public override bool CanSeek { get { return false; } }

        public override WaveFormat WaveFormat { get { return Format; } }

        public override long Length { get { return totalBytes; } }

        public override long Position {
            get { return totalBytes - buf.Count; }
            set { throw new NotImplementedException("Seeking not implemented."); }
        }

        public override void Write(byte[] buffer, int offset, int count) {
            buf.Write(buffer, offset, count);
            totalBytes += count;
        }

        public override int Read(byte[] buffer, int offset, int count) {
            return buf.Read(buffer, offset, count);
        }

        public void Reset() {
            totalBytes = 0;
            buf.Reset();
        }
    }
}
